package com.wander.demo;

public class MemoryExample {
    public static void main(String[] args) throws InterruptedException {
        Runtime runtime = Runtime.getRuntime();

        System.out.println("=== Initial State ===");
        printMemoryStats(runtime);

        // 分配 500MB 内存
        byte[] data = new byte[500 * 1024 * 1024];
        System.out.println("\n=== After 500MB Allocation ===");
        printMemoryStats(runtime);

        // 释放内存并强制 GC
        data = null;
        runtime.gc();
        Thread.sleep(1000); // 等待 GC 完成

        System.out.println("\n=== After GC ===");
        printMemoryStats(runtime);
    }
    private static void printMemoryStats(Runtime runtime) {
        System.out.printf("Total: %d MB\n", runtime.totalMemory() / 1024 / 1024);
        System.out.printf("Free: %d MB\n", runtime.freeMemory() / 1024 / 1024);
        System.out.printf("Used: %d MB\n",
                (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024);
        System.out.printf("Max Available: %d MB\n", runtime.maxMemory() / 1024 / 1024);
    }

}
